package com.yuezhu.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatSpinner;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.yuezhu.Model.DictionaryModel;
import com.yuezhu.Model.PlanModel;
import com.yuezhu.R;
import com.yuezhu.activity.MyprojectActivity;
import com.yuezhu.activity.WebActivity;
import com.yuezhu.been.UserMsg;
import com.yuezhu.constante.BusAction;
import com.yuezhu.constomview.DragView;
import com.yuezhu.constomview.DragViewGroups;
import com.yuezhu.control.TaskEngine;
import com.yuezhu.global.ApplicationContext;
import com.yuezhu.global.BaseFragment;
import com.yuezhu.util.LogUtils;
import com.yuezhu.util.LoginOut;
import com.yuezhu.util.MyToast;
import com.yuezhu.util.StringUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class DiantiNumFragment extends BaseFragment implements View.OnClickListener {
    @InjectView(R.id.bottom_left)
    View bottom_left;
    @InjectView(R.id.bottom_middle)
    View bottom_middle;
    @InjectView(R.id.bottom_right)
    View bottom_right;
    @InjectView(R.id.iv_bottome_left)
    ImageView ivBottomeLeft;
    @InjectView(R.id.iv_bottome_middle)
    ImageView ivBottomeMiddle;
    @InjectView(R.id.iv_bottome_right)
    ImageView ivBottomeRight;
    @InjectView(R.id.part_information_name)
    TextView partInformationName;
    @InjectView(R.id.information_spinner)
    AppCompatSpinner informationSpinner;
    @InjectView(R.id.dragview)
    DragView dragview;
    @InjectView(R.id.drag_groups)
    DragViewGroups dragGroups;
    @InjectView(R.id.fenqu_text1)
    TextView fenquText1;
    @InjectView(R.id.fenqu_text2)
    TextView fenquText2;
    @InjectView(R.id.fenqu_text3)
    TextView fenquText3;
    @InjectView(R.id.fenqu_text4)
    TextView fenquText4;
    @InjectView(R.id.jiben_bengong)
    TextView jibenBengong;
    @InjectView(R.id.jiben_bengong2)
    TextView jibenBengong2;
    @InjectView(R.id.contact_us)
    TextView contact_us;
    @InjectView(R.id.part_jiben)
    LinearLayout partJiben;
    int screen_height = ApplicationContext.getInstance().getScreen_height();
    @InjectView(R.id.jiben_bengong11)
    TextView jibenBengong11;
    @InjectView(R.id.img)
    ImageView img;
    @InjectView(R.id.load_speed)
    AppCompatSpinner loadSpeed;
    @InjectView(R.id.load_weight)
    AppCompatSpinner loadWeight;
    @InjectView(R.id.dianti_num)
    TextView diantiNum;
    @InjectView(R.id.fenqu_num)
    TextView fenqu_num;
    @InjectView(R.id.notice1)
    View notice1;
    @InjectView(R.id.notice2)
    View notice2;
    private int currentAreaIndex = 0;
    private AlertDialog dialog;

    @Override
    public void initview(View view) {

    }

    @Override
    public void setLiseners() {
        ivBottomeMiddle.setOnClickListener(this);
        ivBottomeMiddle.setImageResource(R.drawable.message_left);
        ivBottomeMiddle.setVisibility(View.VISIBLE);
        bottom_middle.setVisibility(View.VISIBLE);
        ivBottomeLeft.setVisibility(View.GONE);
        bottom_left.setVisibility(View.GONE);
        ivBottomeRight.setVisibility(View.GONE);
        bottom_right.setVisibility(View.GONE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dianti_num, container, false);
        ButterKnife.inject(this, view);
        setLiseners();
        setParm();
        EventBus.getDefault().register(this);
        loadSpeed.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                loadSpeed.setDropDownVerticalOffset(loadSpeed.getHeight());
                PlanModel.Area area = PartitionnformationFragment.areaArrayListOfPlan.get(currentAreaIndex);
                double selectedSpeed = Double.parseDouble((String) loadSpeed.getSelectedItem());
                if (selectedSpeed != area.liftSpeed) {
                    area.liftSpeed = selectedSpeed;
                    updateArea(area);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        loadWeight.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                loadWeight.setDropDownVerticalOffset(loadWeight.getHeight());
                PlanModel.Area area = PartitionnformationFragment.areaArrayListOfPlan.get(currentAreaIndex);
                String selectedWeight = (String) loadWeight.getSelectedItem();
                if (selectedWeight.contains("(")) {
                    selectedWeight = selectedWeight.substring(0, selectedWeight.indexOf("("));
                }
                int weight = Integer.parseInt(selectedWeight);
                if (weight != area.liftLoad) {
                    area.liftLoad = weight;
                    updateArea(area);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        if (UserMsg.getInstance().getLevel() == 0) {
            notice1.setVisibility(View.VISIBLE);
            notice2.setVisibility(View.VISIBLE);
        } else {
            notice1.setVisibility(View.INVISIBLE);
            notice2.setVisibility(View.INVISIBLE);
        }
        notice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyToast.showDefaltToast("基本版仅支持选择部分运行速度， 高级版无此限制。 升级说明请参见菜单中的关于页面");
            }
        });
        notice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyToast.showDefaltToast("基本版仅支持选择部分标称载重， 高级版无此限制。 升级说明请参见菜单中的关于页面");
            }
        });
        contact_us.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent data=new Intent(Intent.ACTION_SENDTO);
                data.setData(Uri.parse("mailto:service@zcloud-online.com"));
                data.putExtra(Intent.EXTRA_SUBJECT, "寻求更多垂直交通顾问意见");
                data.putExtra(Intent.EXTRA_TEXT, "请说明您要咨询的内容及其它联系方式，我们将会尽快与您取得联系");
                startActivity(data);
            }
        });
        return view;
    }

    private void updateArea(final PlanModel.Area area) {
        HashMap<String, String> map = new HashMap<>();
        map.put("areaId", area.areaId);
        map.put("bldgId", area.bldgId);
        map.put("planId", area.planId);
        map.put("areaName", area.areaName);
        map.put("floorBottom", area.floorBottom + "");
        map.put("floorTop", area.floorTop + "");
        map.put("type", area.type + "");
        map.put("areaGrade", area.areaGrade + "");
        map.put("skyLobby", area.skyLobby + "");
        map.put("floorHeight", area.floorHeight + "");
        map.put("floorValue", area.floorValue + "");
        map.put("targetPerson", area.targetPerson + "");
        map.put("liftSpeed", area.liftSpeed + "");
        map.put("liftLoad", area.liftLoad + "");
        map.put("liftNum", area.liftNum + "");
        map.put("persionRatio", area.persionRatio + "");
        TaskEngine.getInstance().startUpdateAreaTask(queue, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject json) {
                try {
                    String respCode = json.getString("respCode");
                    if (!StringUtil.equal(respCode, "OK")) {
                        try {
                            if (json.getInt("respNo") == 999) {
                                LoginOut.LoginOut(getActivity());
                            }
                        } catch (Exception e) {
                            MyToast.showDefaltToast("获取数据失败");
                        }
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    } else {
                        Map<String, String> map = new HashMap<>();
                        map.put("bldgId", area.bldgId);
                        TaskEngine.getInstance().startGetAreaTask(queue, map, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject json) {
                                LogUtils.e("获取项目列表" + "sec" + json.toString());
                                try {
                                    String respCode = json.getString("respCode");
                                    if (!StringUtil.equal(respCode, "OK")) {
                                        try {
                                            if (json.getInt("respNo") == 999) {
                                                LoginOut.LoginOut(getActivity());
                                            }
                                        } catch (Exception e) {
                                            MyToast.showDefaltToast("获取数据失败");
                                        }
                                        if (dialog != null && dialog.isShowing()) {
                                            dialog.dismiss();
                                        }
                                    } else {
                                        PlanModel planModel = new PlanModel(json);
                                        PartitionnformationFragment.areaArrayListOfPlan = planModel.getAreaArrayListByPlanId(area.planId);
                                        Collections.sort(PartitionnformationFragment.areaArrayListOfPlan);
                                        setData(PartitionnformationFragment.areaArrayListOfPlan.get(currentAreaIndex));
                                        try {
                                            dragGroups.getDragViewFenQuText(currentAreaIndex).setText(PartitionnformationFragment.areaArrayListOfPlan.get(currentAreaIndex).areaName);
                                            dragGroups.getDragViewOtherInfoText(currentAreaIndex).setText(PartitionnformationFragment.areaArrayListOfPlan.get(currentAreaIndex).liftSpeed + "m/s\n" +
                                                    PartitionnformationFragment.areaArrayListOfPlan.get(currentAreaIndex).liftLoad + "kg\n" + PartitionnformationFragment.areaArrayListOfPlan.get(currentAreaIndex).liftNum + "台");
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        if (dialog != null && dialog.isShowing()) {
                                            dialog.dismiss();
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    MyToast.showDefaltToast("获取数据失败");
                                    if (dialog != null && dialog.isShowing()) {
                                        dialog.dismiss();
                                    }
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                MyToast.showDefaltToast("获取数据失败");
                                if (dialog != null && dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    MyToast.showDefaltToast("获取数据失败");
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                MyToast.showDefaltToast("获取数据失败");
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("更新中......"); //设置内容
        builder.setCancelable(false);
        dialog = builder.create();
        dialog.show();
    }

    private void setSpinner(final ArrayList<String> list, final AppCompatSpinner spinner) {
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, list) {
            @Override
            public View getDropDownView(int position, View convertView,
                                        ViewGroup parent) {
                View view = LayoutInflater.from(getContext()).inflate(R.layout.item_spinner,
                        null);
                TextView label = (TextView) view
                        .findViewById(R.id.spinner_item_label);
                label.setText(list.get(position) + "");
                return view;
            }

            @Override
            public String getItem(int position) {
                return list.get(position);
            }
        };
        spinner.setAdapter(arrayAdapter);
    }

    public void show() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("获取项目列表"); //设置内容
        builder.setCancelable(false);
        final Dialog dialog1 = builder.create();
        dialog1.show();
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 4; i++) {
                    dragGroups.getDragViewFenQuText(i).setVisibility(View.GONE);
                    dragGroups.getDragViewOtherInfoText(i).setVisibility(View.GONE);
                }
                dragGroups.setView(PartitionnformationFragment.areaArrayListOfPlan, MyprojectActivity.currentProjectModel.bldgFloors);
                dragGroups.setViewSelected(0);
                for (int i = 0; i < PartitionnformationFragment.areaArrayListOfPlan.size(); i++) {
                    PlanModel.Area area = PartitionnformationFragment.areaArrayListOfPlan.get(i);
                    dragGroups.getDragViewFenQuText(i).setVisibility(View.VISIBLE);
                    dragGroups.getDragViewOtherInfoText(i).setVisibility(View.VISIBLE);
                    dragGroups.getDragViewFenQuText(i).setText(area.areaName);
                    dragGroups.getDragViewOtherInfoText(i).setText(area.liftSpeed + "m/s\n" + area.liftLoad + "kg\n" + area.liftNum + "台");
                }
                setData(PartitionnformationFragment.areaArrayListOfPlan.get(0));
                currentAreaIndex = 0;
                fenqu_num.setText("分区数量 " + PartitionnformationFragment.areaArrayListOfPlan.size());
                partInformationName.setText(MyprojectActivity.currentProjectModel.bldgName);
                if (dialog1 != null && dialog1.isShowing()) {
                    dialog1.dismiss();
                }
            }
        }, 500);
        for (int i = 0; i < 4; i++) {
            dragGroups.getDragViewFenQuText(i).setVisibility(View.GONE);
            dragGroups.getDragViewOtherInfoText(i).setVisibility(View.GONE);
        }
        dragGroups.setView(PartitionnformationFragment.areaArrayListOfPlan, MyprojectActivity.currentProjectModel.bldgFloors);
        dragGroups.setViewSelected(0);
        for (int i = 0; i < PartitionnformationFragment.areaArrayListOfPlan.size(); i++) {
            PlanModel.Area area = PartitionnformationFragment.areaArrayListOfPlan.get(i);
            dragGroups.getDragViewFenQuText(i).setVisibility(View.VISIBLE);
            dragGroups.getDragViewOtherInfoText(i).setVisibility(View.VISIBLE);
            dragGroups.getDragViewFenQuText(i).setText(area.areaName);
            dragGroups.getDragViewOtherInfoText(i).setText(area.liftSpeed + "m/s\n" + area.liftLoad + "kg\n" + area.liftNum + "台");
        }
    }

    private void setData(PlanModel.Area area) {
        ArrayList<String> speeds = DictionaryModel.getInstance().getLiftSpeed(area.liftSpeed);
        setSpinner(speeds, loadSpeed);
        int loadindex = speeds.indexOf(area.liftSpeed + "");
        if (loadindex < 0) {
            loadindex = 0;
        }
        loadSpeed.setSelection(loadindex);
        ArrayList<String> loads = DictionaryModel.getInstance().getLiftLoad(area.liftLoad);
        setSpinner(loads, loadWeight);
        int weightIndex = 0;
        for (String s : loads) {
            if (s.startsWith(area.liftLoad + "")) {
                weightIndex = loads.indexOf(s);
                break;
            }
        }
        loadWeight.setSelection(weightIndex);
//        loadSpeed.setText(area.liftSpeed + "");
//        loadWeight.setText(area.liftLoad + "");
        diantiNum.setText(area.liftNum + "");
    }

    @Subscribe
    public void onEventMainThread(BusAction.DiantiDragViewClicked event) {
        currentAreaIndex = event.index;
        dragGroups.setViewSelected(event.index);
        setData(PartitionnformationFragment.areaArrayListOfPlan.get(event.index));
    }

    private void setParm() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) dragview.getLayoutParams();
        params.height = screen_height / 2;
        dragGroups.setViewCount(4, false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        EventBus.getDefault().post(new BusAction.mymessPart1());
//        BusProvider.getInstance().post(new DataChangedEvent(BusAction.MYMESS_PART1));
    }

    @OnClick(R.id.img)
    public void onClick() {
        Intent intent = new Intent(getActivity(), WebActivity.class);
        intent.putExtra("weburl", "http://www.zcloud-\n" +
                "online.com/meservice/vtc");
        startActivity(intent);
    }
}
